package com.example.demo.controller;

import com.example.demo.dao.AppDao;
import com.example.demo.dao.CollectDao;
import com.example.demo.entity.App;
import com.example.demo.entity.Collect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app")
public class AppController {
    @Autowired
    private AppDao appDao;
    @Autowired
    private CollectDao collectDao;

    @RequestMapping("list")
    public Object list(@RequestParam(value = "name", required = false) String name, @RequestParam(value = "type", required = false) String type, HttpSession session) {
        if (StringUtils.isEmpty(name))
            name = null;

        String userId = session.getAttribute("USER_ID").toString();

        List<App> apps = appDao.queryAllByLimit(name, type);
        List<Integer> appIds = apps.stream().map(a -> a.getId()).collect(Collectors.toList());
        if (userId == null || userId =="" || appIds==null ||appIds.size()<1) {
            return apps;
        }
        List<Collect> collects = collectDao.queryByAppIdAndUserId2(appIds, userId);
        List<String> collect = collects.stream().map(c -> c.getName()).collect(Collectors.toList());
        apps.stream().forEach(a -> {
            if (collect.contains(a.getName())) {
                a.setCollect(true);
            }
        });
        return apps;
    }

}
